import express from 'express'
import multer from 'multer';
import path from 'path'
import cors from 'cors';
import { fileURLToPath } from 'url';

const app = express();
const port = 3000;

// 获取当前模块的目录名
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 启用所有 CORS 请求
app.use(cors());

// 设置静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 设置存储引擎
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 上传文件存储目录
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname)); // 使用时间戳作为文件名，保留原始扩展名
  }
});

// 初始化上传
const upload = multer({ storage: storage });

// 创建上传路由
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }
  // 返回符合 Vditor 规范的 JSON 响应
  res.json({
    code: 0, // 0 表示成功
    data: {
      errFiles: [],
      succMap: {
        [req.file.originalname]: `http://localhost:${port}/uploads/${req.file.filename}`
      }
    }
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
}); 